<script setup>
import { ref, defineExpose } from 'vue';
import { useDocumentStore } from "@/stores/documentStore.js";
import { ElMessage } from 'element-plus'

const documentStore = useDocumentStore();
const visible = ref(false);
const currentDocId = ref(null);
const signImage = ref('');

const show = (docId) => {
  currentDocId.value = docId;
  visible.value = true;
};

const handleUpload = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    signImage.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);
};


const handleSubmit = () => {
  if (!signImage.value) {
    ElMessage.error('请上传签名图片');
    return;
  }
  documentStore.signDocument(currentDocId.value, signImage.value).then(() => {
    ElMessage.success('文档签名成功');
    visible.value = false;
  }).catch(() => {
    ElMessage.error('文档签名失败');
  });
};

defineExpose({
  show
});
</script>

<template>
  <el-dialog v-model="visible" title="文档签名" width="50%">
    <el-upload
        class="upload-demo"
        action=""
        :show-file-list="false"
        :on-change="handleUpload"
        :auto-upload="false"
    >
      <el-button type="primary">点击上传签名图片</el-button>
      <template #tip>
        <div class="el-upload__tip">请上传您的签名图片</div>
      </template>
    </el-upload>

    <div v-if="signImage" class="sign-preview">
      <h4>签名预览:</h4>
      <img :src="signImage" alt="签名预览" style="max-width: 200px; max-height: 100px;" />
    </div>

    <div class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认签名</el-button>
    </div>
  </el-dialog>
</template>


<style scoped>
.upload-demo {
  margin-bottom: 20px;
}
.sign-preview {
  margin-top: 20px;
  padding: 10px;
  border: 1px dashed #ddd;
}
.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>